package com.android.fragmentdemo
import android.graphics.Bitmap
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.MotionEvent
import android.view.animation.LinearInterpolator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.android.fragmentdemo.adapters.LooperImgItemAdapter
import com.android.fragmentdemo.databinding.ActivityLooperImgBinding
import com.android.fragmentdemo.defineanimator.DefineDefaultItemAnimator
import com.android.fragmentdemo.definervlayoutmanager.LooperLayoutManager4
import com.android.fragmentdemo.definervlayoutmanager2.LoopingItemDecoration
import com.android.fragmentdemo.definervlayoutmanager2.LoopingLayoutManager
import com.android.fragmentdemo.snaphelper.ViewPagerSnapHelper
import com.android.fragmentdemo.util.UrlConvertBitmapUtil
import com.hengfoxwolf.commonbase.base.BaseActivity
import com.hengfoxwolf.commonbase.base.databeans.DataCase
import java.lang.ref.WeakReference

class LooperImgActivity : BaseActivity<ActivityLooperImgBinding>() {

    private lateinit var mAdapter0: LooperImgItemAdapter

    private lateinit var mAdapter1: LooperImgItemAdapter

    private var mRecyclerViewPool: RecyclerView.RecycledViewPool? = null

    private val picStrList by lazy {
        mutableListOf<String>()
    }

    private val mHandler by lazy {
        HHHandler(this@LooperImgActivity)
    }

    override fun getLayoutId(): Int = R.layout.activity_looper_img

    override fun init(savedInstanceState: Bundle?) {

        picStrList.add(IMG_URL1)
        picStrList.add(IMG_URL2)
        picStrList.add(IMG_URL3)
        picStrList.add(IMG_URL4)
        picStrList.add(IMG_URL5)
        picStrList.add(IMG_URL6)
        picStrList.add(IMG_URL7)
        picStrList.add(IMG_URL8)
        picStrList.add(IMG_URL9)
        picStrList.add(IMG_URL10)
        picStrList.add(IMG_URL11)
        picStrList.add(IMG_URL12)
        picStrList.add(IMG_URL13)
        picStrList.add(IMG_URL14)
        picStrList.add(IMG_URL15)
        picStrList.add(IMG_URL16)
        picStrList.add(IMG_URL17)
        picStrList.add(IMG_URL18)
        picStrList.add(IMG_URL19)
        picStrList.add(IMG_URL20)


        val dataSet = createDataSet()

        mRecyclerViewPool = RecyclerView.RecycledViewPool()
        mRecyclerViewPool!!.setMaxRecycledViews(0, dataSet.size * 3 / 4)

        mAdapter0 = LooperImgItemAdapter(this@LooperImgActivity)
        mAdapter0.itemDataSet = dataSet

        mAdapter1 = LooperImgItemAdapter(this@LooperImgActivity)
        mAdapter1.itemDataSet = dataSet

        mBinding.rv0Img.apply {
            layoutManager = LoopingLayoutManager(this@LooperImgActivity, LinearLayoutManager.HORIZONTAL, false)
            //layoutManager = LooperLayoutManager4(getDimensionValue(R.dimen.dp_5))
            addItemDecoration(LoopingItemDecoration(resources.getDimension(R.dimen.dp_5).toInt()))
            //item宽高不变且item高度相似，使用可以提高性能。
            setHasFixedSize(true)
            //自定义动画 防止闪烁
            //setItemAnimator(DefineDefaultItemAnimator())
            setRecycledViewPool(mRecyclerViewPool)
            //屏幕外缓存
            setItemViewCacheSize(dataSet.size * 3 / 4)
            adapter = mAdapter0
        }

        mBinding.rv1Img.apply {
            layoutManager = LoopingLayoutManager(this@LooperImgActivity, LinearLayoutManager.HORIZONTAL, false)
            setRecycledViewPool(mRecyclerViewPool)
            //屏幕外缓存
            setItemViewCacheSize(dataSet.size * 3 / 4)
            addItemDecoration(LoopingItemDecoration(resources.getDimension(R.dimen.dp_5).toInt()))
            //item宽高不变且item高度相似，使用可以提高性能。
            setHasFixedSize(true)
            //自定义动画 防止闪烁
            //setItemAnimator(DefineDefaultItemAnimator())
            //layoutManager = LooperLayoutManager4(getDimensionValue(R.dimen.dp_5))
            adapter = mAdapter1
        }

        //ViewPagerSnapHelper()
        //ViewPagerSnapHelper().attachToRecyclerView(mBinding.rv0Img)

//        UrlConvertBitmapUtil.convertUrlToBitmap(this@LooperImgActivity,object : ILoadDataCallback<MutableList<Bitmap>> {
//            override fun loadDataSuccess(data: MutableList<Bitmap>) {
//                mAdapter0.setItemDataSet(data)
//                mAdapter1.setItemDataSet(data)
//
                mHandler.sendEmptyMessageDelayed(MSG_DO_SCROLL1, 2000)

                mHandler.sendEmptyMessageDelayed(MSG_DO_SCROLL2, 2000)
//            }
//        })
    }

    override fun onDestroy() {
        super.onDestroy()
        mHandler.removeCallbacksAndMessages(null)
    }

    private fun createDataSet(): MutableList<DataCase> {
        val dataSet = mutableListOf<DataCase>()
        for (i in 0.until(20)) {
            dataSet.add(DataCase(picStrList[i % picStrList.size], i))
        }
        return dataSet
    }

    private fun doLooperScroll1() {
        //index = (++index) % mAdapter0.itemDataSet!!.size
        //mBinding.rv0Img.smoothScrollToPosition(index)

        mBinding.rv0Img.smoothScrollBy(
            getDimensionValue(R.dimen.dp_30),
            0,
            LinearInterpolator(),
            SCROLLING_TIME
        )

//        mBinding.rv0Img.dispatchTouchEvent(MotionEvent.obtain(
//            0,
//            0,
//            MotionEvent.ACTION_DOWN,
//            0F,
//            0F,
//            0,
//        ))

//        mBinding.rv0Img.dispatchTouchEvent(MotionEvent.obtain(
//            0,
//            0,
//            MotionEvent.ACTION_MOVE,
//            -getDimensionValue(R.dimen.dp_30).toFloat(),
//            0F,
//            0,
//        ))

        mHandler.sendEmptyMessageDelayed(MSG_DO_SCROLL1, SCROLLING_TIME.toLong())
    }

    private fun doLooperScroll2() {
        //mBinding.rv1Img.smoothScrollBy(getDimensionValue(R.dimen.dp_30) * -1, 0)

        mBinding.rv1Img.smoothScrollBy(
            getDimensionValue(R.dimen.dp_30) * -1,
            0,
            LinearInterpolator(),
            SCROLLING_TIME
        )

        mHandler.sendEmptyMessageDelayed(MSG_DO_SCROLL2, SCROLLING_TIME.toLong())
    }

    private class HHHandler(activity: LooperImgActivity) : Handler(Looper.getMainLooper()) {
        private val weakReference = WeakReference(activity)
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            val tempActivity = weakReference.get() ?: return
            when (msg.what) {
                MSG_DO_SCROLL1 -> {
                    tempActivity.doLooperScroll1()
                }
                MSG_DO_SCROLL2 -> {
                    tempActivity.doLooperScroll2()
                }
            }
        }
    }

    companion object {
        const val MSG_DO_SCROLL1 = 0x01
        const val MSG_DO_SCROLL2 = 0x02

        const val MINE_TAG = "LooperImgActivity"

        const val SCROLLING_TIME = 200

        const val IMG_URL10 = "http://b247.photo.store.qq.com/psb?/V11ZojBI312o2K/63aY8a4M5quhi.78*krOo7k3Gu3cknuclBJHS3g1fpc!/b/dDXWPZMlBgAA"
        const val IMG_URL1 = "https://i-blog.csdnimg.cn/direct/64a022052d784204b362262d803a11a5.jpeg"
        const val IMG_URL2 = "https://i-blog.csdnimg.cn/direct/1ca5160e71a94edda653ca85c604b999.png#pic_center"
        const val IMG_URL3 = "https://i-blog.csdnimg.cn/img_convert/a978a54f0363191fae40c80ebff07fbb.png"
        const val IMG_URL4 = "https://i-blog.csdnimg.cn/direct/1423d1581b0c46568373af2b3306fe38.png"
        const val IMG_URL5 = "https://i-blog.csdnimg.cn/direct/566cf7f541fa4d34971862ea1f98cde5.png"
        const val IMG_URL6 = "https://i-blog.csdnimg.cn/img_convert/8c6adb571109bd2c8f517311df83ef51.webp?x-oss-process=image/format,png"
        const val IMG_URL7 = "https://i-blog.csdnimg.cn/direct/9598a0c0de6442398ffa49f9fa8c6171.png"
        const val IMG_URL8 = "https://i-blog.csdnimg.cn/direct/41ca6ea86a6c480cbbed8a2e000a2cb0.png"
        const val IMG_URL9 = "https://i-blog.csdnimg.cn/direct/1b43177db0024383872a012efc8934ea.png"
        const val IMG_URL11 = "https://i-blog.csdnimg.cn/img_convert/e18f735c4db72a6729c2ac41077b7dd0.png"
        const val IMG_URL12 = "https://i-blog.csdnimg.cn/img_convert/a0afa4672a3b62e28b1b9d0c3db0b7f0.webp?x-oss-process=image/format,png"
        const val IMG_URL13 = "https://i-blog.csdnimg.cn/img_convert/1614e5273237a7aa6afa279d6115bc19.webp?x-oss-process=image/format,png"
        const val IMG_URL14 = "https://i-blog.csdnimg.cn/direct/72971b6782fc464a98eecc81015540de.png#pic_center"
        const val IMG_URL15 = "https://i-blog.csdnimg.cn/img_convert/4763533824063a338fd7b2cfcd78cbbe.webp?x-oss-process=image/format,png"
        const val IMG_URL16 = "https://i-blog.csdnimg.cn/direct/dcec8d8e479347beae1eb8d69689ce6e.jpeg"
        const val IMG_URL17 = "https://i-blog.csdnimg.cn/blog_migrate/07c0aace28dbf37d03951f27038daf98.png"
        const val IMG_URL18 = "https://i-blog.csdnimg.cn/direct/38150f52b0594fe7860fd00c9806b32f.jpeg"
        const val IMG_URL19 = "https://i-blog.csdnimg.cn/direct/e7581a3ec1694f32af1b0cf2eb9a12e5.png"
        const val IMG_URL20 = "https://i-blog.csdnimg.cn/direct/07fc15a1630b45f5996783f430a49a2d.png"
    }
}